package org.example.repository;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;

@Slf4j
public class RepositoryRunner implements CommandLineRunner, ApplicationContextAware {

    private final TodoTests todoTests;
    private final TestExecutor testExecutor;
    private ApplicationContext applicationContext;

    public RepositoryRunner(TodoTests todoTests, TestExecutor testExecutor) {
        this.todoTests = todoTests;
        this.testExecutor = testExecutor;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void run(String... args) throws InterruptedException {
        testExecutor.initialize();
        testExecutor.execute(
                () -> todoTests.queryAll(),
                () -> todoTests.queryPagination(3, 3),
                () -> todoTests.queryById(2),
                () -> todoTests.queryFirstByTitle("task 3"),
                () -> todoTests.queryByIds(2, 4),
                () -> todoTests.countAll(),
                () -> todoTests.countByIdGte(3),
                () -> todoTests.updateById(5)
        );
        testExecutor.shutdown();
        closeApplication();
    }

    private void closeApplication() {
        log.info("close application");
        ((ConfigurableApplicationContext) applicationContext).close();
    }
}